﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace PMS.SANY.Util
{
    public static partial class Extention
    {
        /// <summary>
        /// 把系统所有Business添加到ServiceCollection
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddBusService(this IServiceCollection services)
        {
            string rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var busAssembly = Assembly.LoadFrom(Path.Combine(rootPath, "PMS.SANY.Business.dll"));
            var busTypes = busAssembly.GetTypes().Where(w => w.Name.EndsWith("Business")).ToList();
            foreach (var busType in busTypes)
            {
                var busInterface = busType.GetInterfaces().Where(w => w.Name.EndsWith("Business")).FirstOrDefault();
                if (busInterface == null) continue;
                if (typeof(ITransientDependency).IsAssignableFrom(busType))
                    services.AddTransient(busInterface, busType);
                if (typeof(IScopedDependency).IsAssignableFrom(busType))
                    services.AddScoped(busInterface, busType);
                if (typeof(ISingletonDependency).IsAssignableFrom(busType))
                    services.AddSingleton(busInterface, busType);
            }
            return services;
        }
    }
}
